
/**
 * 判断是否对象
 * @param {*} target
 * @returns {Boolean}
 */
export const isObject = (target) => Object.prototype.toString.call(target) === '[object Object]';

/**
 * 判断是否空对象
 * @param {*} target
 * @returns {Boolean}
 */
export const isEmptyObject = (target) => {
  if (isObject(target)) {
    const keyArray = Object.keys(target)
    if (keyArray.length === 0) {
      return true
    }
    return false
  }
  return true
}

/**
 * 比较版本号大小
 * @param {String} version1
 * @param {String} version2
 * @returns -1 | 0 | 1
 */
export const compareVersion = (version1 = '', version2 = '') => {
  const sources = version1.split('.');
  const dests = version2.split('.');
  const maxL = Math.max(sources.length, dests.length);
  let result = 0;
  for (let i = 0; i < maxL; i++) {
    let preValue = sources.length > i ? sources[i] : 0;
    let preNum = isNaN(Number(preValue)) ? preValue.charCodeAt() : Number(preValue);
    let nextValue = dests.length > i ? dests[i] : 0;
    let nextNum =  isNaN(Number(nextValue)) ? nextValue.charCodeAt() : Number(nextValue);
    if (nextNum > preNum) {
      result = 1;
      break;
    } else if (nextNum < preNum) {
      result = -1;
      break;
    }
  }
  return result;
}

/**
 * 判断是否有类似SQL语句
 * @param {*} value
 * @returns {Boolean}
 */
const checkIsSQL = (value = '') => {
  let result = false
  const lowerCaseString = `${value}`.toLocaleLowerCase();
  const SQL_ENUM = [
    'select', 'union', 'asc', 'desc',
    'like', 'exec', 'from', 'into',
    'update', 'insert', 'delete', 'create',
    'asc(', 'char(', 'chr(', 'drop',
    'table', 'truncat', 'where', 'join',
    'count', 'alter', 'exists', 'or',
    'and', 'order by', 'group by', 'cast'
  ]
  SQL_ENUM.forEach(keyword => {
    if (lowerCaseString.includes(keyword)) {
      result = true    }
  })
  return result
}

/**
 * 判断是否有XSS语句
 * @param {*} value
 * @returns {Boolean}
 */
const checkIsXSS = (value = '') => {
  var res1 = (new RegExp("\\b(document|onload|eval|script|img|svg|onerror|javascript|alert)\\b")).test(value);
  var res2 = (new RegExp("<","g")).test(value);
  var res3 = (new RegExp(">","g")).test(value);
  return res1 || res2 || res3
}

/**
 * 判断前端传参是否存在非法字符
 * @param {*} params
 * @returns {Boolean}
 */
export const checkParamsIsSafe = (params = {}) => {
  let result = true
  if (isObject(params)) {
    for (let key in params) {
      const isSQL = checkIsSQL(params[key])
      const isXSS = checkIsXSS(params[key])
      if (isSQL || isXSS) {
        result = false
      }
    }
  }
  return result
}